<template>
    <div>
        <div ref="editor" style="text-align:left"></div>
    </div>
</template>

<script>
  import WangEditor from 'wangeditor'
  // import {encode, decode} from '../../utils/htmlUtils'
  import imageUploader from '../uploader/image-uploader'
  import {getUniqueFileName} from '../../utils/fileUtils'

  /* 先调用setContent，用来初始化内容及七牛云token */
  export default {
    name: 'editor',
    props: {
      content: {
        type: String,
        required: true
      }
    },
    data () {
      return {
        editor: null
      }
    },
    methods: {
      setContent (input) {
        if (this.editor) {
          // let html = decode(input)
          this.editor.txt.html(input)
        }
      },
      initCustomerUploader () {
        this.editor.customConfig.customUploadImg = async (files, insert) => {
          let ossInfo = await this.getOSSInfo()
          let [token, domain] = [ossInfo.token, ossInfo.domain]
          let observer = {
            complete: (res) => {
              let sourceLink = domain + '/' + res.key
              insert(sourceLink)
            }
          }
          let arrFile = [...files]
          arrFile.forEach(file => {
            let key = getUniqueFileName(file.name)
            imageUploader(file, key, token, observer)
          })
        }
      },
      async getOSSInfo () {
        let url = '/sys/oss/imguptoken'
        let res = await this.$http({
          url: this.$http.adornUrl(url),
          method: 'post'
        })
        return res.data
      }
    },
    mounted () {
      this.editor = new WangEditor(this.$refs.editor)

      // 绑定文本事件
      this.editor.customConfig.onchange = html => {
        let content = this.editor.txt.text()
        console.log(content)
        // let encodedHtml = encode(html)
        this.$emit('change', html)
      }

      // 配置上传图片
      this.editor.customConfig.uploadImgMaxSize = 2 * 1024 * 1024
      this.initCustomerUploader()
      // this.editor.customConfig.uploadImgShowBase64 = true

      // 配置菜单
      this.editor.customConfig.menus = [
        'head',  // 标题
        'bold',  // 粗体
        'fontSize',  // 字号
        'fontName',  // 字体
        'italic',  // 斜体
        'underline',  // 下划线
        'strikeThrough',  // 删除线
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'list',  // 列表
        'justify',  // 对齐方式
        'quote',  // 引用
        'emoticon',  // 表情
        'image',  // 插入图片
        'table',  // 表格
        // 'video',  // 插入视频
        'code',  // 插入代码
        'undo',  // 撤销
        'redo'  // 重复
      ]

      // 创建实例
      this.editor.create()
      this.setContent(this.content)
    }
  }
</script>
